// 碳排同类对比
var numberFormate = iot.getNumberFormat("0.00");
var timeFormatMap = {
    'year': "%Y-%m",
    'month': "%Y-%m-%d",
    'day': "%Y-%m-%d %H",
    'hour': "%Y-%m-%d %H:%m"
};

/**
 * 通过空间id和时间获取用电对应的sql
 * @param workSpace
 * @param time
 * @returns {string}
 */
function getSqlBySns(sns, format, startTime, endTime) {
    return "select dev.sn, es.`name`, sum(win.dvalue) totalSum, DATE_FORMAT(win.the_time, '" + format + "')time\n" +
    " from iot_dev_data_win win\n" +
    " inner join iot_dev dev on dev.id = win.dev_id\n" +
    " inner join energy_struc_prop esp on win.dev_id = esp.dev_id and win.data_type = esp.`name`\n" +
    " inner join energy_struc es on esp.energy_struc_id = es.id\n" +
    " where dev.sn in (" + sns + ")\n" +
    " and esp.type = 1 and field_type = '用量'\n" +
    " and (win.the_time like '" + startTime +"%'\n" +
    " or win.the_time like '" + endTime + "%')\n" +
    " group by dev.sn, time";
}

dev.action = function(resp,param){
    //是否算总还是单
    var totalOrSingle = param.selectType;
    if (totalOrSingle == null){
        totalOrSingle = "total";
    }
    var theTime = param.time;
    var preYearTime = getPreYearTime(theTime);
    var workSpace = param.workSpace;
    var db = iot.db();
    var timeSub = parseInt(theTime.substring(0, 4));

    var result1 = db.queryOne("select level, name, pid from energy_struc where id = " + workSpace);
    var strSql;
    if (result1.level == '1') {
        strSql = " and level = 1";
    } else {
        strSql = " and level = " + result1.level + " and name = '" + result1.name + "'";
    }

    //获取当前选择年份产量
    var yieldResult = db.queryOne("select SUM(dvalue) totalSum from iot_dev_data_win" +
        " where dev_id = 278 and the_time like '"+ theTime +"%'");
    var totalYield = yieldResult.totalSum;

    // 计算郑州工厂上一年产量
    var preYearSingleResult = db.queryOne("select SUM(dvalue) totalSum from iot_dev_data_win" +
        " where dev_id = 278 and the_time like '"+ preYearTime +"%'");
    var preYearYield = 0;
    if (preYearSingleResult.totalSum) {
        preYearYield = preYearSingleResult.totalSum;
    }

    var factoryNames = db.qry("select name from energy_struc where level = 1 and type = '碳排'");

    var result = 0;
    if (timeSub >= 2019) {
        // 当前年份的用量
        result = db.qry("select es.factory, res.es_id, res.totalSum, es.name from energy_struc es " +
            " INNER JOIN (select esp.energy_struc_id es_id, SUM(dev_win.dvalue) totalSum " +
            " from iot_dev_data_win dev_win," +
            " (select dev_id, name, energy_struc_id from energy_struc_prop where type = 2 and name = '碳排'" +
            " and energy_struc_id in (select id from energy_struc where type = '碳排'" + strSql + ")) esp " +
            " where dev_win.dev_id = esp.dev_id and dev_win.data_type = esp.name" +
            " and dev_win.the_time like '"+ theTime +"%'" +
            " group by esp.energy_struc_id) res" +
            " on es.id = res.es_id order by totalSum desc");

        // 计算郑州工厂上一年总量的同比的数据
        var preYearResult = db.queryOne("select esp.name,SUM(dev_win.dvalue) totalSum from iot_dev_data_win dev_win," +
            " (select * from energy_struc_prop where type = 2 and name = '碳排' and energy_struc_id = "+ workSpace +") esp" +
            " where dev_win.dev_id = esp.dev_id" +
            " and dev_win.data_type = esp.name" +
            " and dev_win.the_time like '"+ preYearTime +"%'");
        var preYearTotalSum = 0;
        if (preYearResult.totalSum) {
            preYearTotalSum = preYearResult.totalSum;
        }

        var factoryList = iot.list();
        var count = 0;
        var preValue = "";
        result.forAll(function (item) {
            // 如果数值一样，则排名不变化
            if (!item.totalSum.equals(preValue)) {
                preValue = item.totalSum;
                ++count;
            }
            //判断当前选择总数还是单车
            if (totalOrSingle.equals("total")) {
                var increase = "0%";
                if (item.totalSum && preYearTotalSum != 0) {
                    var gain = (item.totalSum - preYearTotalSum) / preYearTotalSum; // 计算同比差值
                    increase = (gain * 100).toFixed(1) + "%";
                }
                factoryList.add({rank: count, name: item.factory, workshop: item.name, useNum: numberFormate.format(item.totalSum), increase: increase});
            }else if (totalOrSingle.equals("single")) {
                var sum = 0; // 当前年份的单车用量
                if (item.totalSum && totalYield){
                    sum = item.totalSum / totalYield;
                }
                var increase = "0%";
                var preYearSingle = 0;
                if (preYearTotalSum != 0 && preYearYield != 0) {
                    preYearSingle = preYearTotalSum / preYearYield; // 上一年的单车用量
                    if (sum != 0 && preYearSingle != 0) {
                        var toFixedSum = numberFormate.format(sum);
                        var toFixedPreYearSingle = numberFormate.format(preYearSingle);
                        var gain = (toFixedSum - toFixedPreYearSingle) / toFixedPreYearSingle;
                        increase = (gain * 100).toFixed(1) + "%";
                    }
                }
                factoryList.add({rank: count, name: item.factory, workshop: item.name, useNum: numberFormate.format(sum), increase: increase});
            }
        })

        // 如果工厂数据没有，则赋值为0
        for (var i in similarFactoryList) {
            var flag = false;
            for (var key in factoryList) {
                if (similarFactoryList[i].equals(factoryList[key].name)) {
                    flag = true;
                }
            }
            if (!flag) {
                factoryList.add({rank: count + 1, name: similarFactoryList[i], workshop: result1.name, useNum: 0, increase: "0%"});
            }
        }
        var jsData = {
            content : factoryList
        };
        resp.setJsData(jsData);

    } else { // 计算2019年之前的数据

        // 今年的计算统计数据
        var totalCarbon = 0;
        var eleGasResult = 0;
        // 定义上一年数据的变量
        var preTotalCarbon = 0;
        var preYearElectricityResult = 0;
        var preYearGasResult = 0;

        //工厂  E001._用量*系数 +  G001.用量*系数
        var sns = ""; // 所有工厂电和燃气的设备编号sn
        factoryNames.forAll(function (item) {
            if (frameworkIdToDevSn[item.name] && frameworkIdToDevSn[item.name][workSpace] && frameworkIdToDevSn[item.name][workSpace].ele) {
                var sn = frameworkIdToDevSn[item.name][workSpace].ele;
                sns += (sns + "'" + sn + "',");
            }
            if (frameworkIdToDevSn[item.name] && frameworkIdToDevSn[item.name][workSpace] && frameworkIdToDevSn[item.name][workSpace].gas) {
                var sn = frameworkIdToDevSn[item.name][workSpace].gas;
                sns += (sns + "'" + sn + "',");
            }
        })
        // 去掉最后一个逗号
        sns = sns.substring(0, sns.length - 1);
        var timeType = iot.getTimeByFormat(theTime);
        var format = timeFormatMap[timeType];
        var preTime = iot.getRingTime(theTime);
        eleGasResult = db.qry(getSqlBySns(sns, format, theTime, preTime)); // 所有工厂电和燃气数据的结果
        /**
         * 开始遍历计算碳排的数据(电数据 * 系数 + 燃气数据 * 系数)
         */



        if(electricityResult.totalSum){
            totalCarbon = electricityResult.totalSum * modulus[timeSub].ele;
        }
        if(gasResult && gasResult.totalSum){
            totalCarbon = totalCarbon + gasResult.totalSum * modulus[timeSub].gas;
        }
        // 环比时间的计算数据
        if (preYearElectricityResult.totalSum) {
            preTotalCarbon = preYearElectricityResult.totalSum * modulus[timeSub].ele;
        }
        if (preYearGasResult.totalSum) {
            preTotalCarbon = preTotalCarbon + preYearGasResult.totalSum * modulus[timeSub].gas;
        }
        var factoryList = iot.list();

        factoryNames.forAll(function (item) {
            if (item.factory.equals()) {
                //判断当前选择总数还是单车
                if (totalOrSingle.equals("total")) {
                    var increase = "0%";
                    if (totalCarbon != 0 && preTotalCarbon != 0) {
                        var gain = (totalCarbon - preTotalCarbon) / preTotalCarbon;
                        increase = (gain * 100).toFixed(1) + "%";
                    }
                    factoryList.add({rank: 1, name: 'ZZ', workshop: result1.name, useNum: numberFormate.format(totalCarbon), increase: increase});
                }else if (totalOrSingle.equals("single")) {
                    // 当前年的单车碳排
                    if (totalCarbon != 0 && totalYield != 0){
                        totalCarbon = totalCarbon / totalYield;
                    }
                    var preYearSingleCarbon = 0; // 上一年的单车碳排
                    // 计算上一年的单车碳排
                    if (preTotalCarbon != 0 && preYearYield != 0) {
                        preYearSingleCarbon = preTotalCarbon / preYearYield;
                    }
                    var increase = "0%";
                    // 计算同比涨幅
                    if (totalCarbon != 0 && preYearSingleCarbon != 0) {
                        var toFixedTotalCarbon = numberFormate.format(totalCarbon);
                        var toFixedPreYearSingleCarbon = numberFormate.format(preYearSingleCarbon);
                        var gain = (toFixedTotalCarbon - toFixedPreYearSingleCarbon) / toFixedPreYearSingleCarbon;
                        increase = (gain * 100).toFixed(1) + "%";
                    }
                    factoryList.add({rank: 1, name: 'ZZ', workshop: result1.name, useNum: numberFormate.format(totalCarbon), increase: increase});
                }
            }
        })
        var jsData = {
            content : factoryList
        };
        resp.setJsData(jsData);
    }

}
